import React from 'react';
import '../../static/brief/index.styl'
import moment from 'moment';
import {Link as Linko} from 'react-router-dom'

import Docxtemplater from 'docxtemplater'
import ImageModule from 'docxtemplater-image-module'
import JSZip from 'jszip'
import JSZipUtils from 'jszip-utils'
import saveAs from 'jszip/vendor/FileSaver.js'
import {docUrl} from '../../static/examples/template.docx'

import echarts from 'echarts' 

import axios from 'axios'

import {
  Steps, Icon, Button,Row,Col, Table, Divider, Tabs, Input, DatePicker,
  TimePicker,message
} from 'antd';
import Brief from './index'

// import Briefing from './briefing'

// import { connect } from 'react-redux'

// import {temchange} from '../../actions/brief'

import '../../static/brief/step.styl'

import api from '../../common/request'

const Step = Steps.Step;
const TabPane = Tabs.TabPane;
const format = 'HH:mm';

/*const customDot = (dot, {status, index}) => (
  <Icon type="check-circle" style={{fontSize: '16px'}}/>
);*/



export default class BriefList extends React.Component {
  constructor(props){
    super(props);
    this.state={
      InValue:'',
      startTime1:"00:00:00",
      startdate:this.startDate(),
      endtime:this.nowTime(),
      endtidate:this.endDate(),
      data:[]
    }
    this._rendderList=this._rendderList.bind(this)
    this.dateChangeds=this.dateChangeds.bind(this)
    this.dateChangets=this.dateChangets.bind(this)
    this.dateChangede=this.dateChangede.bind(this)
    this.dateChangete=this.dateChangete.bind(this)
    this.link=this.link.bind(this)
  }
  //默认开始时间
  startDate(){
    return moment().format('YYYY-MM-DD')
  }
  //默认结束时间
  endDate(){
    return moment().format('YYYY-MM-DD')
  }
  //默认时间
  nowTime(){
    return moment().format('HH:mm:ss')
  }
  componentDidMount() {
    this._rendderList()
  }
  dateChangeds(data,tatstring){
    this.setState({
      startdate:tatstring
    })
  }
  dateChangede(data,tatstring){
    this.setState({
      endtidate:tatstring
    })
  }

  dateChangets(time,timestring){
    this.setState({
      startTime1:timestring
    })
  }
  dateChangete(time,timestring){
    this.setState({
      endtime:timestring
    })
  }
  inchange(e){
    this.setState({
      InValue:e.target.value
    })
  }
  delebiref(id){
    api.birefdelete(id).then(res=>{
      if(res.data.success){
        message.success('删除成功')
        this._rendderList()
      }else{
        message.error(res.data.message)
      }
    })
  }
  _rendderList(){
    let strTime=this.state.startdate+' '+this.state.startTime1
    let endTime=this.state.endtidate+' '+this.state.endtime
    api.briefList(this.state.InValue,endTime,strTime).then(res=>{
      if(res.data.success){
          this.setState({
              data:res.data.data
          })
      }else{
        message.error(res.data.message)
      }
    })
  }
  handleSerch(){
    this._rendderList()
  }
  han(index){
    //alert(index)
  }
  link(){
    this.props.history.push('/briefList')
  }

  //简报word生成
  async getBrieftem(id){
    let loadDocx = path => new Promise(r => JSZipUtils.getBinaryContent(path, (err, d) => r(d)))
    let loadJson = path => fetch(path).then(d => d.json())
    let chart = echarts.init(this.refs.main)
    let imageModule = new ImageModule({
      centered: false,
      getImage: d => Uint8Array.from(atob(d.slice(22)), c => c.charCodeAt(0)),
      getSize: () => ([400, 200])
    })
    function genChart0(d){
      let option = {
        animation: false,
        tooltip : {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        series : [{
          name: '访问来源',
          type: 'pie',
          radius : '55%',
          center: ['50%', '60%'],
          data: d,
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      chart.setOption(option)
      return chart.getDataURL()
    }

    function genChart1(d){
      let option = {
        animation: false,
        color: ['#3398DB'],
        tooltip : {
          trigger: 'axis',
          axisPointer : {            // 坐标轴指示器，坐标轴触发有效
            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis : [{
          type : 'category',
          data : d.map(d => d.name),
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            interval: 0
          }
        }],
        yAxis : [{
          type : 'value'
        }],
        series : [{
          type:'bar',
          barWidth: '60%',
          data: d.map(d => d.value)
        }]
      }
      chart.clear()
      chart.setOption(option)
      return chart.getDataURL()
    }

    Promise.all([
      loadDocx(docUrl),
      axios.post('vrv-monitor-platform-web/briefing/queryById',{id:id}).then(
        function(reponse){
          console.log(reponse)
          return reponse
        }
      )
    ]).then(([content, jsondata]) => {
      console.log(content)
      var zip = new JSZip(content);
      console.log(zip)
      console.log(imageModule)
      let doc = new Docxtemplater().attachModule(imageModule).loadZip(zip)
      let d = jsondata.data.data
      let str1 = ''
      let websiteLeader = d.websiteLeader
      function setwebsite(arr){
        let t = arr.reduce((a,d) => a +d.doc_count,0)
        let m = `本报告就加入素材的文章进行分析，共有${t}篇相关素材。`
        arr.forEach(d =>{
          let str = d.websiteName+d.doc_count+'篇,占比'+(d.doc_count/t*100).toFixed(2)+'%,'
          m += str
        });
        m+=`目前主要的报道集中在${websiteLeader}等几大站点。详细报告请继续浏览。`
        str1 = m
      }
      setwebsite(JSON.parse(d.website))
      let arr = JSON.parse(d.sensitivity)
      let t = arr.reduce((a,d) => a +d.doc_count,0)
      let m = arr.filter(d => d.key ==2)[0].doc_count
      let mz = ((m/t)*100).toFixed(2)
      let nm = t - m
      let nmz = ((nm/t)*100).toFixed(2)
      let str2 = `监测主题相关信息${t}条，其中敏感${m}条，敏感占比${mz}%，非敏感${nm}条，非敏感占比${nmz}%`
      doc.setData({
        str1:str2,
        str2:str1,
        date: d.createTime,
        organizationName: d.organizationName,
        suggestion: d.suggestion,
        ...JSON.parse(d.titles),
        infos: JSON.parse(d.importantOpinion).map((d, i) => ({
          num: i + 1,
          title: d.title,
          date: new Date(d.poTime).toISOString().slice(0, 10),
          source: d.source || d.webSite,
          mg: !!d.positiveOrNegative
        })),
        chart32: genChart0(JSON.parse(d.website).map(d => ({name: d.websiteName, value: d.doc_count}))),
        chart33: genChart1(JSON.parse(d.liveness)),
      })
      doc.render()
      let out = doc.getZip().generate({
        type: "blob",
        mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      })
      saveAs(out, `${d.briefingName}.docx`)
      

      

    })
  }
  render() {
    const columns = [{
      className: 'briefingName',
      title: '简报名称',
      dataIndex: 'briefingName',
      width: '40%',
      key: 'briefingName',
    }, {
      className: 'createTime',
      title: '生成时间',
      dataIndex: 'createTime',
      width: '45%',
      key: 'createTime',
    }, {
      title: '操作',
      key: 'action',
      width: '15%',
      render: (text, record) => (
        <span>
          <span><Linko to={"/editor?id="+record.id}><Icon type="eye-o" style={{fontSize: '16px'}}/></Linko></span>
          <Divider type="vertical"/>
          <span onClick={()=>this.delebiref(record.id)}><Icon type="delete" style={{fontSize: '16px'}}/></span>
          {/* <span onClick={()=>this.getBrieftem(record.id)}>下载</span> */}
        </span>
      ),
    }];
    return (
      <div className="brief briefList step01">
          <div className="top">
          <div className="title">
            <span className="left-title">简报制作</span>
            <span className="right-title">半自动化生成或舆情分析报</span>
          </div>
          <div className="section">
            <Row>
              <Col span={18}>
              <p>如果您有更专业的简报需求,请点击联系<a>人工简报</a>服务</p>
              <div className="steps-con">
                <div className="steps" style={{position: 'relative'}}>
                  <Steps  current={0}>
                    <Step title=""  onClick={this.link}/>
                    <Step title="" />
                    <Step title="" />
                    <Step title="" />
                  </Steps>
                  </div>
                  <div className="step-info">
                    <div>步骤1-选择素材</div>
                    <div>步骤2-确认素材</div>
                    <div>步骤3-选择样式</div>
                    <div>步骤4-生成简报</div>
                  </div>
              </div>
              </Col>
              <Col span={6}>
                <div className="generate">
                  <div className="c-btn creat-btn">
                    <Button type="primary"><Linko to={"/step01"}>创建简报</Linko></Button>
                  </div>
                </div>
              </Col>
            </Row>
          </div>
        </div>
        <div className="bottom">
          <div className="bottom-inner">
            <Tabs defaultActiveKey="1">
              <TabPane tab="简报模板" key="1">
                <Brief choIndex={(index)=>this.han(index)}/>
              </TabPane>
              <TabPane tab="简报列表" key="2">
                <div className="toolbar" style={{textAlign: 'right'}}>
                  <Input placeholder="请输入简报名称" style={{width: '200px', marginRight: 10}} onChange={(e)=>this.inchange(e)}/>
                  <DatePicker defaultValue={moment(this.state.startdate)} onChange={this.dateChangeds}/>
                  <TimePicker defaultValue={moment(0, format)} format={format}
                              style={{marginLeft: 10}} onChange={this.dateChangets}/>
                  <span style={{margin: '0 10px'}}>To</span>
                  <DatePicker defaultValue={moment(this.state.endtidate)} onChange={this.dateChangede}/>
                  <TimePicker defaultValue={moment(this.state.endtime,'HH:mm')} format={format}
                              style={{marginLeft: 10}} onChange={this.dateChangete}/>
                  <Button type="primary" style={{marginLeft: 10}} onClick={()=>this.handleSerch()}>搜索</Button>
                  <div ref='main' style={{width: '600px',height:'300px',display:'none'}}></div>
                </div>
                <Table rowKey="id"
                columns={columns}
<<<<<<< HEAD
                dataSource={this.state.data} 
                pagination={false}
                /></TabPane>
=======
                 dataSource={this.state.data} 
                 pagination={false}/></TabPane>
>>>>>>> 8ce3c03230ff2bd4d74522c57da66d8a750f2178
            </Tabs>
            {/*<Tabs defaultActiveKey="1">*/}
              {/*<TabPane tab="素材库" key="1">*/}
              {/*</TabPane>*/}
              {/*<TabPane tab="舆情列表" key="2">*/}
              {/*</TabPane>*/}
              {/*<TabPane tab="全文搜索" key="3">*/}
              {/*</TabPane>*/}
            {/*</Tabs>*/}
          </div>
        </div>
      </div>
    );
  }
}